<template>
  <layout>
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          icon="search"
          @click="search()"
        >搜索</a-button>
        <a-button
          class="upload-button"
          type="primary"
          auth="import-old-data.import"
          @click="handlerTableAdd"
        >
          上传文件
          <!-- <input type="file"> -->
        </a-button>
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <!-- 产品列表 -->
    <a-table
      :columns="tableColumns"
      :dataSource="tableData"
      :rowKey="record => record.id"
      :customRow="customTableRow"
      :pagination="false"
      :scroll="{
        y: tableClientHeight,
        x: '100%'
      }"
      @change="handleTableChange"
      bordered
    >
      <template
        slot="file_type"
        slot-scope="row"
      >
        {{getLabel(row.file_type, [], 'file_type')}}
      </template>
      <template
        slot="statu"
        slot-scope="row"
      >
        {{getLabel(row.statu, [], 'statu')}}
      </template>

      <template
        slot="file_nam"
        slot-scope="row"
      >
        <a-popconfirm
          title="您确认要下载该文件?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerDownload(row)"
        >
          <a href="#">{{row.file_nam}}</a>
        </a-popconfirm>
      </template>
      <template
        slot="file_size"
        slot-scope="row"
      >
        {{row.file_size}}
      </template>
      <template
        slot="usr_nickname"
        slot-scope="row"
      >
        {{row.usr_nickname}}<br>{{row.i_time}}
      </template>
      
      <!-- 按钮区 -->
      <template
        slot="action"
        slot-scope="row"
      >
        
        <!-- <a-popconfirm
          title="您确认要下载该文件?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerDownload(row)"
        >
          <a-button
            type="link"
          >[数据文件下载]</a-button>
        </a-popconfirm> -->
        <a-button
          type="link"
          @click="handleTableEdit(row)"
          :auth="{
            keys: ['import-old-data.edit', `${row.i_uid}` === `${user.usr_id}`],
            relate: 'and'
          }"
          v-if="!overtime(row.i_time)"
        >[编辑]</a-button>

        <!-- <a-popconfirm
          title="您确认要该数据提交等候入库?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerSubmitQueue(row)"
        >
          <a-button
            type="link"
            auth="import-old-data.await-queue"
          >[提交等候入库]</a-button>
        </a-popconfirm> -->
        
        <a-popconfirm
          title="您确认要删除该条数据?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="tableDel(row)"
        >
          <a-button
            type="link"
            v-if="!overtime(row.i_time)"
            :disabled="`${row.i_uid}` !== `${user.usr_id}`"
          >删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :show-total="showTotal"
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      @ok="handleFromSubmit"
      centered
      @cancel="visible = false"
      :confirm-loading="visibleLoading"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        v-bind="formItemLayout"
      >
        <template slot="file-upload" slot-scope="{params}">
          <a-button class="upload-button">
            <input type="file" @change="(e) => handlerChangeUpload(e, params)">
            点击上传文件
          </a-button>
          <p v-if="file" style="line-height: 24px;">当前选择文件：<br>{{ file && file.name }}</p>
        </template>
      </custom-form>
    </a-modal>

    <!-- <MemberImport ref="MemberImport" :isPreview="true" @previewSuccess="previewSuccess" />
    <FamilyImport ref="FamilyImport" :isPreview="true" @previewSuccess="previewSuccess" />
    <GrainImport ref="GrainImport" :isPreview="true" @previewSuccess="previewSuccess" /> -->

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { fileServices, IFile } from '@/common/services/file'
import { userServices } from '@/common/services'
import { userModule } from '@/store/modules/user'


@Component({
  components: {
    Layout: TableLayout,
    CustomForm
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  get user() {
    return userModule.userInfo
  }

  get projects () {
    return userModule.projects
  }

  // 产品列表搜索条件
  public tableSearch = {
    page: 1,
    pageSize: 15,
  }

  public formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 17 },
  }

  // 上传文件列表
  public file: File | null = null
  public data: any[] = []

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '存档编号',
      dataIndex: 'iid',
      key: 'iid',
      width: 80
    },
    {
      title: '行政区名称',
      dataIndex: 's_a_nam_all',
      key: 's_a_nam_all',
      width: 200,
      form: {
        type: 'a-input',
        placeholder: '',
        isShowFrom: false,
        disabled: true
      }
    },
    {
      title: '兑付年份',
      dataIndex: 'pro_year',
      key: 'pro_year',
      width: 80,
      form: {
        type: 'a-select',
        placeholder: '请选择项目兑付年份',
        showSearch: true,
        isShowQuery: true,
        dict: [],
        validate: '*'
      }
    },
    // {
    //   title: '项目兑付年份',
    //   dataIndex: 'pro_year',
    //   key: 'pro_year',
    //   width: 150,
    //   form: {
    //     type: 'a-year-picker',
    //     placeholder: '请选择项目兑付年份',
    //     isShowQuery: true,
    //     validate: '*'
    //   }
    // },
    {
      title: '文件类型',
      dataIndex: 'task_nam',
      key: 'task_nam',
      width: 80,
      form: {
        type: 'a-select',
        placeholder: '请选择文件类型',
        isShowQuery: true,
        dict: [],
        validate: '*'
      }
    },
    {
      title: '文件名称',
      // dataIndex: 'file_nam',
      key: 'file_nam',
      width: 300,
      scopedSlots: { customRender: 'file_nam' },
      form: {
        type: 'a-input',
        placeholder: '请输入存档文件名称',
        isShowFrom: false,
        isShowQuery: true
      }
    },
    {
      title: '文件大小',
      // dataIndex: 'file_nam',
      key: 'file_size',
      width: 80,
      scopedSlots: { customRender: 'file_size' },
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      form: {
        type: 'a-input',
        placeholder: '请输入存档文件名称',
        isShowFrom: false,
      }
    },
    {
      title: '文件上传',
      dataIndex: 'file_name',
      key: 'file_name',
      form: {
        type: 'a-upload',
        placeholder: '请选择上传的文件',
        isShowList: false,
        slot: 'file-upload',
        validate: '*'
      }
    },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      width: 250,
      form: {
        type: 'a-textarea',
        placeholder: '请输入备注',
        rows: 4
      }
    },
    {
      title: '上传人/日期',
      width: 160,
      key: 'usr_nickname',
      scopedSlots: { customRender: 'usr_nickname' }
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  public tableApi = {
    list: fileServices.getFiles,
    add: fileServices.uploadFile,
    edit: fileServices.uploadFile,
    del: fileServices.delete,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  public mounted() {
    // this.getData()
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.getData()
    this.getProjectsList()
    this.getYears()
  }

  public async getData() {
    const res = await this.getTableList()
    // this.tableData = res.data || []
  }

  public getProjectsList() {
    // userServices.getProjectsList({
    //   s_a_id: this.currentAreaId
    // }).then(_ => {
    //   this.changeDict('task_nam', _.data.map(item => {
    //     return {
    //       label: item.task_nam,
    //       value: item.task_nam
    //     }
    //   }))
    // })

    this.changeDict('task_nam', [
      '一般农户',
      '种粮大户',
      '全数据包',
      '其他'
    ].map(item => {
      return {
        label: item,
        value: item
      }
    }))
  }

  public getYears() {
    const currentYear = new Date().getFullYear();
    const minYear = 2000
    this.changeDict('pro_year', new Array(currentYear - minYear).fill(1).map((_, index: number) => {
      return {
        label: currentYear - index,
        value: currentYear - index
      }
    }))
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: any) {
    this.tableEdit(Object.assign({}, row))
  }

  public handlerTableAdd() {
    this.file = null;
    this.tableAdd()
    this.visibleTitle = "文件上传"
  }

  public handlerChangeUpload(e: Event, params: Record<string, string>) {
    // @ts-ignore
    const files = e.target.files
    const size = 10;
    if (files[0].size > size * 1024 * 1024) {
      this.$message.error(`文件大小不能超过${size}M`)
      return
    }
    this.file = files[0]
    params.file_name = this.file?.name || ''
    // @ts-ignore
    e.target.value = null
  }

  // 提交等候队列
  public handleFromSubmit() {
    this.handleSubmit({}, true, (params) => {
      let temp: Record<string, string> = {}
      for (let i in params) {
        if (!params[i]) {
          temp[i] = ''
        } else {
          temp[i] = params[i]
        }
      }
      return this.file ? {
        ...temp,
        myfile: this.file
      } : params
    })
  }

  // 判断是否超时
  public overtime(time: string) {
    return Date.now() / 1000 -  new Date(time).getTime() / 1000 > 86400
  }

   public handlerDownload(row: IFile) {
    const loading = this.$message.loading({
      content: '文件下载中，请稍后',
      duration: 0
    })
    fileServices.download({
      iid: row.iid
    }).then(_ => {
      // 判断是否异常
      if (_.data.type === 'application/json') {
        const reader = new FileReader()
        reader.readAsText(_.data, 'utf-8')
        reader.onload = () => {
          const data = JSON.parse(reader.result as string)
          this.$message.error(data.msg)
        }
        
      } else {
        // @ts-ignore
        const filename = _.headers['content-disposition'].replace(/(.*)(?=filename=)/g, '').replace('filename=', '');
        const data = _.data
        const url = window.URL.createObjectURL(data)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', decodeURI(filename))
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.$message.success('导出成功')
      }
      
    }).finally(() => {
      loading()
    })
  }
}
</script>

<style scoped>
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
</style>
